#include "FindWord.h"
#include <iostream>

FindWord::FindWord(void)
{
	wordsFoundCount = 0;
	keyChars = 0;
	charCount = 0;
	wordLength = 0;
}

FindWord::FindWord(string word)
{
	wordsFoundCount = 0;
	wordLength = word.length();
	keyChars = new char[wordLength + 1];
	strcpy (keyChars, word.c_str());
	charCount = new int[wordLength +1];
	for (int i = 0; i <= wordLength; i++)
	{
		charCount[i] = 0;
	}
}

FindWord::~FindWord(void)
{
	if (keyChars != 0) delete keyChars;
	if (charCount != 0) delete charCount;
}

void FindWord::notify(event e, string data)
{
	bool flag;
	char inChar;
	switch (e)
	{
	case KEY_EVENT: // Check to see if the key event character is one we're looking for
		inChar = data.c_str()[0];
		flag = false;
		for (int i = 0; i < wordLength; i++)
		{
			if (inChar == keyChars[i])
			{
				charCount[i]++;
				flag = true;
				break;
			}
		}
		if (flag)
		{
			for (int i = 0; i < wordLength; i++)
			{
				flag &= (charCount[i] > 0); 
			}
		}
		if (flag)
		{
			for (int i = 0; i < wordLength; i++) charCount[i]--;
			wordsFoundCount++;
			cout << "    [FindWord::" << keyChars << "] Found a '" << keyChars <<"'." << endl;
		}
		break;
	case CLASS_EVENT:
		if (data == "PRINT")
		{
			cout << "    [FindWord::" << keyChars << "] Found " << wordsFoundCount << " instances of " << keyChars << "." << endl;
		}
		break;
	default:;
	}
}

bool FindWord::subscribe( event e)
{
	return Notifier::getInstance()->subscribe(this, e);
}

bool FindWord::unsubscribe( event e)
{
	return Notifier::getInstance()->unsubscribe(this, e);
}